import pandas as pd
import numpy as np
import statsmodels.api as sm
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用SimHei字体
plt.rcParams['axes.unicode_minus'] = False  # 正确显示负号
# 读取合并数据集，假设文件名为 '合并数据集.xlsx'
data = pd.read_excel('合并数据集.xlsx')
data = data.iloc[1:]  # 删除第一行
print(data.columns)
# 提取材料、温度、频率、磁芯损耗、励磁波形
material = data['材料']  # 材料
temperature = data['温度，oC']  # 温度
frequency = data['频率，Hz']  # 频率
core_loss = data['磁芯损耗，w/m3']  # 磁芯损耗
waveform = data['励磁波形']  # 励磁波形

# 将材料和励磁波形转为分类变量
material = material.astype('category')
waveform = waveform.astype('category')

# 创建一个数据框用于回归分析
tbl = pd.DataFrame({
    'material': material,
    'temperature': temperature,
    'frequency': frequency,
    'waveform': waveform,
    'core_loss': core_loss
})

# 回归模型：分析材料、温度、频率、励磁波形的独立及交互作用
model = smf.ols('core_loss ~ material * temperature * frequency * waveform', data=tbl).fit()

# 显示回归模型的结果
print('回归模型结果：')
print(model.summary())

# 显示模型系数的估计值和显著性水平
print('模型的系数及其显著性：')
print(model.params)

# 绘制残差图，检查模型拟合情况
plt.figure()
plt.scatter(model.fittedvalues, model.resid)
plt.axhline(0, color='red', linestyle='--')#比赛结束前最后一天售后群发布无水印可视化结果+无标注代码【可直接提交】为了防止倒卖， 论文写作过程中遗留数个致命问题，无关代码，该问题解决方式仅在官网授权售后群答疑，盗卖方式购买资料不提供答疑，感谢理解2024年研赛资料助攻购买链接+说明https://docs.qq.com/doc/p/e03d6bffc00b392932b7dc1fbcf746ef9b086a8a
plt.title('残差图')
plt.xlabel('拟合值')
plt.ylabel('残差')
plt.grid()
plt.show()

# 分析交互作用
# 1. 温度-励磁波形的交互作用
unique_temperatures = temperature.unique()
unique_waveforms = waveform.unique()
mean_loss = np.zeros((len(unique_temperatures), len(unique_waveforms)))

for i, temp in enumerate(unique_temperatures):
    for j, wave in enumerate(unique_waveforms):
        idx = (temperature == temp) & (waveform == wave)
        mean_loss[i, j] = core_loss[idx].mean()

# 绘制交互作用图
plt.figure()
for j, wave in enumerate(unique_waveforms):
    plt.plot(unique_temperatures, mean_loss[:, j], '-o', label=wave)#比赛结束前最后一天售后群发布无水印可视化结果+无标注代码【可直接提交】为了防止倒卖， 论文写作过程中遗留数个致命问题，无关代码，该问题解决方式仅在官网授权售后群答疑，盗卖方式购买资料不提供答疑，感谢理解2024年研赛资料助攻购买链接+说明https://docs.qq.com/doc/p/e03d6bffc00b392932b7dc1fbcf746ef9b086a8a

plt.legend(title='Waveform', loc='best')
plt.xlabel('Temperature')
plt.ylabel('Mean Core Loss')
plt.title('温度与励磁波形的交互作用')
plt.grid()
plt.show()

# 2. 材料-温度的交互作用
unique_materials = material.unique()
mean_loss_material_temp = np.zeros((len(unique_temperatures), len(unique_materials)))

for i, temp in enumerate(unique_temperatures):
    for j, mat in enumerate(unique_materials):
        idx = (temperature == temp) & (material == mat)
        mean_loss_material_temp[i, j] = core_loss[idx].mean()

# 绘制交互作用图
plt.figure()
for j, mat in enumerate(unique_materials):
    plt.plot(unique_temperatures, mean_loss_material_temp[:, j], '-o', label=mat)

plt.legend(title='Material', loc='best')
plt.xlabel('Temperature')
plt.ylabel('Mean Core Loss')
plt.title('材料与温度的交互作用')
plt.grid()
plt.show()

# 3. 材料-励磁波形的交互作用
mean_loss_material_waveform = np.zeros((len(unique_materials), len(unique_waveforms)))

for i, mat in enumerate(unique_materials):
    for j, wave in enumerate(unique_waveforms):
        idx = (material == mat) & (waveform == wave)
        mean_loss_material_waveform[i, j] = core_loss[idx].mean()

# 绘制交互作用图
plt.figure()
for j, wave in enumerate(unique_waveforms):
    plt.plot(range(len(unique_materials)), mean_loss_material_waveform[:, j], '-o', label=wave)

plt.xticks(range(len(unique_materials)), unique_materials)
plt.legend(title='Waveform', loc='best')
plt.xlabel('Material')
plt.ylabel('Mean Core Loss')
plt.title('材料与励磁波形的交互作用')
plt.grid()
plt.show()

# 找出损耗最小的条件
predicted_losses = model.predict(tbl)
min_loss = predicted_losses.min()
min_idx = predicted_losses.idxmin()
optimal_conditions = tbl.iloc[min_idx]

print('最优条件下的磁芯损耗最小值及相应的条件：')
print(min_loss)
print(optimal_conditions)
